﻿using System;
using System.IO;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YArchitech.LIB;
using YArchitech.Revit;

namespace YArchitech.HVAC
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CreateRisePipeFile : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			UIApplication application = commandData.Application;
			Document document = application.ActiveUIDocument.Document;
			Transaction transaction = null;
			Result result;
			try
			{
				transaction = new Transaction(document, "CreateFile");
				transaction.Start();
				this.SetRisePipeInfo(application);
				new AssistSystemType().createRiserPipeFilter(document, "管道立管线宽");
				document.Regenerate();
				transaction.Commit();
				YJKMessageBox.Show("立管线宽设置完成。");
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
				result = Autodesk.Revit.UI.Result.Failed;
			}
			finally
			{
				if (transaction != null && (int)(int)transaction.GetStatus() != 3)
				{
					transaction.RollBack();
				}
			}
			return result;
		}

		public void SetRisePipeInfo(UIApplication uiApp)
		{
			YJKRevitTools.SetInstanceParameter(uiApp, Path.Combine(Product.DataLocation, "HYShared Parameters.txt"), "管道参数", "是否立管", BuiltInCategory.OST_PipeCurves, true);
			foreach (Element element in new FilteredElementCollector(uiApp.ActiveUIDocument.Document).OfCategory(BuiltInCategory.OST_PipeCurves).OfClass(typeof(Pipe)).ToElements())
			{
				Parameter parameter = element.GetParameter("是否立管");
				if (element is Pipe && parameter != null && !parameter.IsReadOnly)
				{
					if (YJKRevitTools.isRiserPipe(element as Pipe))
					{
						parameter.Set("是");
					}
					else
					{
						parameter.Set("否");
					}
				}
			}
		}
	}
}
